import Vue from 'vue'

export const state = () => ({
	header: {},
	exp: 0,
	adminInfo: {},
	tokenuser: {},
	enterprise: {},
	webSetting: {
		address: "",
		copyright: "",
		name: "青猿回收",
		sitelogoimg: "/images/logo-ico.png",
		adminlogoimg: "/images/logo.png",
		telphone: ""
	},
	loadWebSetting: false,
	userdetail: {
		name:'管理员',
		photo: ''
	},
  userid: 0,
  operatorid: 0,
	loadUser: false,
	enterpriseList: [],
	remindCount: 0,
	loading: true,
  socketInit: false,
  visitedViews: [],  // 访问过的页面
  activeView: '/',     // 当前激活的tab
  operator:{ //运营商详情
    balance: null,
    date: "",
    id: 0,
    isproprietary: true,
    name: "",
    city:{
      cityid: 0,
      cityname: "",
    }
  },
  franchise:{ //加盟商详情
    id: 0, 
    name: '',
    balance: 0, 
    paymode: '',
  }
})

export const mutations = {
	//设置上传header
	setHeader(state, token) {
    state.header = {
      Authorization: token
    }
	},
  // 运营商详情
  setOperator(state, operator) {
    state.operator = operator
  },
  // 加盟商详情
  setFranchise(state, franchise) {
    state.franchise = franchise
  },
	//管理员登录状态
	setAdminInfo(state, info) {
		state.adminInfo = info
	},
	//网站信息
	setWebSetting(state, setting) {
		state.webSetting = setting
	},
	setLoadWebSetting(state, status) {
		state.loadWebSetting = status
	},
	//用户信息
	setUser(state, user) {
		state.userdetail = user
	},
  setUserId(state, userid) {
		state.userid = userid
	},
  setOperatorid(state,operatorid){
    state.operatorid = operatorid
  },
	// 消息提醒
	setRemindCount(state, user) {
		state.remindCount = user
	},
	setWebLoading(state, loading) {
		state.loading = loading
	},
  //socket是否初始化
  setSocketInit(state,socketInit){
    state.socketInit = socketInit
  },
  ADD_VISITED_VIEW: (state, view) => {
    // console.log('当前路由对象：', view)
    // console.log('路由meta信息：', view.meta)
    if (state.visitedViews.some(v => v.path === view.path)) return
    state.visitedViews.push(
      Object.assign({}, view, {
        title: view.meta.title || '未命名'
      })
    )
    // if (process.client) {
    //   state.visitedViews.push(
    //     Object.assign({}, view, {
    //       title: document.title || '未命名'
    //     })
    //   )
    // }
  },
  SET_ACTIVE_VIEW: (state, view) => {
    // console.log('[Mutation] SET_ACTIVE_VIEW:', view)
    // 添加安全校验
    if (view && view.path) {
      state.activeView = view.path
    } else if (typeof view === 'string') {
      state.activeView = view
    } else {
      console.error('Invalid view object:', view)
    }
  },
  DEL_VISITED_VIEW: (state, view) => {
    for (const [i, v] of state.visitedViews.entries()) {
      if (v.path === view.path) {
        state.visitedViews.splice(i, 1)
        break
      }
    }
  }
}

export const actions = {
  // 初始化保存全局数据
	setInitData({
		commit,
		state,
    dispatch
	}, lifeData) {
		return new Promise((resolve,reject) => {
			if(lifeData.authorization){
				commit('setHeader', lifeData.authorization)
				commit('setUserId', lifeData.userid)
        commit('setOperatorid', lifeData.operatorid)
				localStorage.setItem('lifeData',JSON.stringify(lifeData))
        
				resolve()
			}else{
        reject()
			}
		});
	},
  // 获取用户信息
  getUserInfo({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve,reject) => {
      this.$axios.get('/User/Detail').then((res) => {
        let user = res
        commit('setUser', user)
        resolve(user)
      })
    })
  },
	// 在线推送信息
	signalrConnection({
		commit,
		state,
		dispatch
	}) {
		//signalr处理
		return new Promise((resolve,reject) => {
      let connection = null
      if(state.socketInit == true){
        resolve(connection)
      }else{
        commit('setSocketInit',true)
        connection = new signalR.HubConnectionBuilder()
        .withUrl(`${Vue.prototype.baseURL}/pushed`, {
          accessTokenFactory: () => {
            return localStorage.getItem("lifeData").authorization; //传入token
          }
        })
        .configureLogging(signalR.LogLevel.Information)
        .withAutomaticReconnect([10000, 4000, 10000, 10000])
        .build()

        resolve(connection)

        //接收消息
        connection.on("RemindCount", function(user, message) {
          console.log("收到的消息1");
          let obj = {
            type: 'RemindCount',
            user:user
          }
          // Vue.prototype.$message({
          // 	type: 'success',
          // 	message: `您有${user.count}条新消息`,
          // 	duration: 5000
          // })

          commit('setRemindCount',user.count)
        });
        connection.on("remind", (user, message)=> {
          console.log("收到的消息2",user);
          let obj = {
            type: 'remind',
            user:user
          }
          // remindType参数说明
          // 用户派单 = 1
          // 出库派单 = 2
          // 用户下单 = 3
          // 小哥拒单 = 4
          // 用户提现 = 5
          // 小哥提现 = 6
          // 订单超时 = 7
          // 小哥提现申请 = 8
          // 散客提现申请 = 9
          // 客户组提现申请 = 10
          // 待核账出库单 = 11
          // 中转站出库订单超时提醒 = 12
          if(obj.user.item.remindType == 3){ //用户下单
            console.log(obj.user.item.relationId)
            Vue.prototype.$notify({
              title: '新的用户订单',
              message: '接收到一条新的用户订单，请处理',
              duration:10000,
              type: 'success',
              onClick: ()=> {
                this.$router.push({
                  path: '/order/user/Views?id='+user.item.relationId
                })
              }
            });
          }
          if(obj.user.item.remindType == 4){ //小哥拒单
            Vue.prototype.$notify({
              title: '小哥拒单',
              message: '小哥拒绝接单，请重新派单',
              duration:10000,
              type: 'success',
              onClick: ()=> {
                this.$router.push({
                  path: '/order/user/Views?id='+user.item.relationId
                })
              }
            });
          }
          if(obj.user.item.remindType == 9){ //用户提现
            Vue.prototype.$notify({
              title: '用户提现申请',
              message: obj.user.item.remarks,
              duration:10000,
              type: 'success',
              onClick: ()=> {
                this.$router.push({
                  path: '/withdrawal/list?status=1'
                })
              }
            });
          }
          if(obj.user.item.remindType == 6){ //小哥提现
            Vue.prototype.$notify({
              title: '小哥提现申请',
              message: '接收到一条新的小哥提现申请，请处理',
              duration:10000,
              type: 'success',
              onClick: ()=> {
                this.$router.push({
                  path: '/withdrawal/list?status=2'
                })
              }
            });
          }
          if(obj.user.item.remindType == 7){ //订单超时
            Vue.prototype.$notify({
              title: '订单超时',
              message: '接单超时，请重新派单',
              duration:10000,
              type: 'success',
              onClick: ()=> {
                this.$router.push({
                  path: '/order/user/Views?id='+user.item.relationId
                })
              }
            });
          }
        });
        connection.on("reload", function(user, message) {
          console.log("reload");
          let obj = {
            type: 'reload',
            user:user
          }
        });

        //发送消息, 需在链接成功后调用
        //connection.invoke('方法名',参数)

        //链接断开
        connection.onclose(function() {
          console.log("websocket连接断开");
          commit('setSocketInit',false)
        });

        connection.start()
      }
		})
	}
}
